package com.example.treehole.ui.page.postDetail

import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import com.example.treehole.service.DataRepository
import com.example.treehole.ui.component.showTreeholeSnackbar
import com.example.treehole.ui.model.Comment
import com.example.treehole.ui.model.CommentType
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

class CreateCommentViewModel :ViewModel(){
    private val _userComment = MutableStateFlow<String>("")
    val userComment:StateFlow<String> = _userComment

    private val _replyUserName = MutableStateFlow<String>("")
    val replyUserName:StateFlow<String> = _replyUserName

    private val _cmtCmtId = MutableStateFlow<Int>(0)
    val cmtCmtId:StateFlow<Int> = _cmtCmtId

    private val _cmtType = MutableStateFlow<CommentType>(CommentType.CommentToPost)
    val cmtType:StateFlow<CommentType> = _cmtType

    val isCommenting = mutableStateOf<Boolean>(false)

    fun updateUserComment(content:String){
        _userComment.value = content
    }
    fun updateReplyUserName(name:String){
        _replyUserName.value = name
    }
    fun updateCmtCmtId(id:Int){
        _cmtCmtId.value = id
    }
    fun updateCommentingState(state:Boolean){
        isCommenting.value = state
    }
    fun updateCmtType(type:CommentType){
        _cmtType.value = type
    }

    suspend fun uploadComment(
        jwlToken:String,
        userId:Int,
        postId:Int
    ):Comment?{
        if(userComment.value.isEmpty()){
            showTreeholeSnackbar("内容不能为空")
            return null
        } else{
            return DataRepository.createCmt(
                jwlToken,
                userId,
                postId,
                cmtType.value.ordinal,
                cmtCmtId.value,
                replyUserName.value,
                userComment.value
            )
        }
    }
}